import React, {PureComponent} from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Alert, message as msg} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FORM_OPTIONS, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {conventSorter} from '../utils';
import styles from './style.css';
import WrappedTag from '../common/WrappedTag';
import {getDealers} from './api';
const FormItem = Form.Item;

class DealerSelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        code: '',
        name: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        sortField: 'code',
        isDesc: false,
        currentCondition: {}
    };
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;

        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    };
    handleFilterPressEnter = (value, name) => {
        this.setState({
            [name]: value
        }, this.onClickSearchBtn);
    };
    onQuery = condition => {
        this.setState({
            isFetching: true
        });
        getDealers(condition).then(res => {
            if(res.ok)
                this.setState({
                    isFetching: false,
                    message: '',
                    data: res.data,
                    currentCondition: condition
                });
            else
                this.setState({
                    isFetching: false,
                    data: [],
                    message: res.message
                });
        });
    };
    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    };
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    };
    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    };
    onChange = (value, name) => {
        this.setState({
            [name]: value
        });
    };

    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }
    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'dealerSelectPanel.radioMessage',
                defaultMessage: '请选择总代'
            }));
        this.props.onSelect(this.state.rows[0]);
    }
    render() {
        const {code, name, isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.code',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.name',
                    defaultMessage: '总代名称'
                }),
                dataIndex: 'name',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.branchCode',
                    defaultMessage: '营销公司编号'
                }),
                dataIndex: 'branchCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.provinceName',
                    defaultMessage: '省份'
                }),
                dataIndex: 'provinceName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.cityName',
                    defaultMessage: '城市'
                }),
                dataIndex: 'cityName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.countyName',
                    defaultMessage: '区县'
                }),
                dataIndex: 'countyName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.contactName',
                    defaultMessage: '联系人'
                }),
                dataIndex: 'contactName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.contactPhone',
                    defaultMessage: '联系人电话'
                }),
                dataIndex: 'contactPhone'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.address',
                    defaultMessage: '联系人地址'
                }),
                dataIndex: 'address'
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };

        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH
        };
        const selectTag = (<span>{this.props.intl.formatMessage({
            id: 'dealerSelectPanel.selectTag',
            defaultMessage: '，已选择'
        })} {this.state.rows.map(tag =>
            <WrappedTag key={tag.id} id={tag.id} closable onClose={this.onCloseTag}>
                {tag.name}
            </WrappedTag>)}</span>);
        const alertMessage = (
            <Row>
                <Col span={18}><span>{this.props.intl.formatMessage({
                    id: 'dealerSelectPanel.alertMessage',
                    defaultMessage: '可以双击行选择'
                })}</span>{this.state.rows.length ? selectTag : ''}</Col>
                <Col span={6} className="col-align-right">
                    <Button type="primary" size="small" onClick={this.onSubmit}>{this.props.intl.formatMessage({
                        id: 'dealerSelectPanel.btn.confirm',
                        defaultMessage: '确认'
                    })}</Button>
                </Col>
            </Row>);

        return (
            <div>
                <Row className="form-standard operation-buttons">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'dealerSelectPanel.code',
                                defaultMessage: '总代编号'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput name="code" value={code}
                                onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'dealerSelectPanel.name',
                                defaultMessage: '总代名称'
                            })}
                            {...FORM_OPTIONS.item}>
                            <TextInput name="name" value={name}
                                onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col
                        span={8}
                        className={styles.selectPanelBtn}>
                        <Button type="primary" onClick={this.onClickSearchBtn}>
                            {this.props.intl.formatMessage({
                                id: 'dealerSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                    </Col>
                </Row>
                <Divider className={styles.divider} />
                <Alert
                    className={styles.alertMargin}
                    type="info"
                    message={alertMessage}
                    showIcon/>
                <Table
                    className={`white-space-nowrap ${styles.tableCursor}`}
                    rowKey="id"
                    dataSource={data.content}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}
                    locale={{
                        emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }}/>
            </div>
        );
    }
}

DealerSelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    intl: PropTypes.object,
};
export default injectIntl(DealerSelectPanel);
